package com.hnqcgczy.controller;

import com.hnqcgczy.service.IUserService;
import com.hnqcgczy.service.impl.UserServiceImpl;
import com.hnqcgczy.utils.MD5Encryptor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码格式
        req.setCharacterEncoding("utf-8");
        //获取请求的账号 密码
        String tuId = req.getParameter("tuId");
        String password = req.getParameter("password");
        String okpassword = req.getParameter("okpassword");
        //将参数输出到控制台，以便测试
        System.out.println(tuId);
        System.out.println(password);
        System.out.println(okpassword);
        if ("".equals(tuId) || "".equals(password)) {
            System.out.println("登陆信息有误-存在空值");
            resp.sendRedirect("/register");
        } else if (!password.equals(okpassword)) {
            System.out.println("两次密码不一致");
            resp.sendRedirect("/register");

        } else {
            //调用服务层方法， 实现注册
            IUserService userService = new UserServiceImpl();
            try {
                //md5加密密码
                String md5pass= MD5Encryptor.encrypt(password);
                boolean flag = userService.reg(tuId, md5pass);
                //判断注册结果
                if (flag) {
                    //注册成功成功跳转到登录
                    System.out.println("ok");
//                resp.sendRedirect("/login.jsp");
                    resp.sendRedirect("/home");
                } else {
                    System.out.println("fail");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
